#coding:utf-8
import re


from rest_framework.exceptions import ValidationError
from rest_framework.serializers import ModelSerializer

from erp_system.models import UserModel

from MSB_ERP.apps.erp_system.serializer.Dept_Serializer import DeptSerializer
from MSB_ERP.apps.erp_system.serializer.role_serializer import BaseRolesSerializer


class UserRegisterSerializer(ModelSerializer):
    #用户注册的序列化
    class Meta:
        model=UserModel
        fields=('id','username','password','phone','real_name')
        extra_kwargs={
            "username":{
                'max_length':12,
                'min_length':2
            },
            'password':{
                'max_length':8,
                'min_length':6,
                'write_only':True
            }

        }

    def validate_phone(self,phone):
        #验证时间号码，自定义一个验证的函数(命名规则：validate_+字段名字)
        if not phone:
            return phone
        else:
            if not re.match(r'^1[3589]\d{9}$',phone):
                raise ValidationError('请输入正确的手机号码')
        return phone

    def create(self, validated_data):
        #重写create，因为用户密码是不能直接插入数据库
        user=UserModel.objects.create_user(**validated_data)
        return user


class UserUpdateOrDeleteSerializer(ModelSerializer):
    #只用于删除和修改：id,phone,real_name,role_id,dept_id

    class Meta:
        model=UserModel
        fields=('id','phone','real_name','roles','dept')



class UserGetSerializer(ModelSerializer):
    #只用于查询用户，返回：id,username,phone,real_name,所有的角色的详细信息，用户所在的部门的详细信息
    roles=BaseRolesSerializer(many=True,read_only=True)#一个用户可以是多个角色，many=True
    dept=DeptSerializer(many=False,read_only=True)#一个用户只有一个部门，不是多条数据many=False
    class Meta:
        model=UserModel
        fields=('id','phone','real_name','roles','dept','username')

from rest_framework import serializers


class ResetPasswordSerializer(ModelSerializer):
    #只用于:修改密码，包含三个参数：原密码，新密码，新密码确认
    new_password=serializers.CharField(write_only=True,required=True)
    confirm_password=serializers.CharField(write_only=True,required=True)

    class Meta:
        model=UserModel
        fields=('id','new_password','password','confirm_password')
        extra_kwargs={
            'password':{'write_only':True},
            'confirm_password':{'write_only':True},
            'new_password':{'write_only':True},
        }

    def validate(self, attrs):
        #表单参数的验证
        password=attrs.get('password')
        new_password=attrs.get('new_password')
        confirm_password=attrs.get('confirm_password')
        if not password:
            raise ValidationError('不能为空')
        if not new_password:
            raise ValidationError('不能为空')
        if not confirm_password:
            raise ValidationError('不能为空')
        if confirm_password != new_password:
            raise ValidationError('密码不一致')
        return attrs


    def save(self, **kwargs):
    #必须重写save函数，否则明文的密码会保持到数据库中
    #self.instance是指当前表单实例所关联的模型对象。它通常在自定义表单中使用，用于获取该表单正在编辑或创建的模型对象。这里就是user模型类 就是user.


        if  not self.instance.check_password(self.validated_data.get('password')):
            raise ValidationError('原密码错误')
        self.instance.set_password(self.validated_data.get('new_password'))
        return self.instance


















